package 回溯;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution3 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);//排序方便剪枝
        dfs(0,new LinkedList(),candidates,target,0);
        return res;
    }
    List<List<Integer>> res = new LinkedList();
    void dfs(int index, List<Integer> path, int[]candidates, int target, int cur){
        if(cur>=target){
            if(cur==target) res.add(new LinkedList(path));
            return;
        }
        for(int i = index ; i<candidates.length;i++){
            if(cur+candidates[i]>target) return;//剪枝，因为原数组已经是递增的了，如果这里就已经大于target了，后续也不用递归了
            path.add(candidates[i]);
            dfs(i,path,candidates,target,cur+candidates[i]);
            path.remove(path.size()-1);
        }
        return;
    }
}
